package bb.lanxing.mvp.model;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.github.mikephil.charting.utils.Utils;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.common.config.Constants;
import bb.lanxing.common.config.UmengEventConst;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.WorkoutDatabaseHelper;
import bb.lanxing.model.database.PacePoint;
import bb.lanxing.model.database.Segment;
import bb.lanxing.model.database.Trackpoint;
import bb.lanxing.model.database.User;
import bb.lanxing.model.database.Workout;
import bb.lanxing.model.jsonlocal.JPoint;
import bb.lanxing.model.jsonlocal.JPointPackage;
import bb.lanxing.model.jsonlocal.JSegment;
import bb.lanxing.model.jsonlocal.JSegmentKm;
import bb.lanxing.model.jsonlocal.JWorkout;
import bb.lanxing.mvp.model.i.IWorkoutSyncModel;
import bb.lanxing.mvp.model.i.ResultListener;
//import bb.lanxing.network.BiciHttpClient;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetSubscribe;
import bb.lanxing.network.TencentClient;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.Enums;
import bb.lanxing.util.AppFileUtils;
import bb.lanxing.util.JsonUtil;
import bb.lanxing.util.Log;
import bb.lanxing.util.debug.SyncLogger;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class WorkoutSyncModelImpl implements IWorkoutSyncModel {
    final private static String TAG = "WorkoutSyncModelImpl";

    private ArrayList<Subscription> subscriptions;


    public void log(String str, Throwable th) {
        if (th != null) {
            if (th instanceof NetSubscribe.ApiException apiException) {
                str = str + " Api code: " + apiException.getCode() + " detail: " + apiException.getMessage();
            }
            SyncLogger.getInstance().log("Workout Sync", str, th);
            return;
        }
        SyncLogger.getInstance().log("Workout Sync", str);
    }

    @Override
    public void getUnUploadWorkout(long j, Subscriber<List<Workout>> subscriber) {
        Observable.just((j)).subscribeOn(Schedulers.io()).flatMap(l -> {
            List<Workout> unUploadWorkouts = Workout.getUnUploadWorkouts(l);
            ArrayList<Workout> arrayList = new ArrayList<>();
            for (Workout workout : unUploadWorkouts) {
                if (workout.getLocSource() == Workout.LOCATION_SOURCE_BICI && !workout.isSynchronise()) {
                    arrayList.add(workout);
                }
            }
            if (!arrayList.isEmpty()) {
                unUploadWorkouts.removeAll(arrayList);
            }
            return Observable.just(unUploadWorkouts);
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber);
    }

    @Override
    public boolean uploadJsonWorkout(List<Workout> list, final ResultListener<Workout, Workout> resultListener) {
        String buildExternalDirectoryPath = AppFileUtils.buildExternalDirectoryPath(Constants.WORKOUT_DIR);
        if (TextUtils.isEmpty(buildExternalDirectoryPath)) {
            App.getContext().showMessage(R.string.sdcard_null);
            log("no extra space", null);
            return false;
        }
        this.subscriptions = new ArrayList<>(list.size());
        for (int i = 0; i < list.size(); i++) {
            final Workout workout = list.get(i);
            final String fileName = buildExternalDirectoryPath + workout.getUuid() + ".bb";
            //todo, sst, decompile error, need debug
            this.subscriptions.add(Observable.just(workout).subscribeOn(Schedulers.io()).flatMap(workout2 -> {
                String md5;
                try {
                    Workout.saveSegmentAndPoints(workout2);
                } catch (JSONException e) {
                    e.printStackTrace();
                    if (resultListener != null) {
                        resultListener.onError(workout2, e);
                    }
                    log("sync save segment and point failed 125: ", e);
                }
                try {
                    md5 = createUploadPackage(workout2, fileName);
                } catch (IOException e2) {
                    e2.printStackTrace();
//                        ResultListener resultListener2 = resultListener;
                    if (resultListener != null) {
                        resultListener.onError(workout2, e2);
                    }
                    log("sync create upload package failed 134: ", e2);
                    md5 = null;
                }
                if (workout2 != null) {
                    int sport = workout2.getSport();
                }
                Log.d(TAG, "upload workout path = " + fileName + " md5 = " + md5);
                if (md5 == null){

                    try{
                        LitePal.beginTransaction();

                        long id = workout2.getId();

                        for (Segment segment : Segment.getByWorkoutId(workout2.getId())) {
                            segment.delete();
                        }
                        for (PacePoint pacePoint : PacePoint.getByWorkoutUuid(workout2.getUuid())) {
                            pacePoint.delete();
                        }
                        for (Trackpoint trackpoint : Trackpoint.getByWorkoutId(workout2.getId())) {
                            trackpoint.delete();
                        }

//                      WorkoutDatabaseHelper.delete(workout2);
                        workout2.delete();


                        LitePal.setTransactionSuccessful();



                    }
                    catch (Exception e3){
                        e3.printStackTrace();
                    }
                    finally {
                        LitePal.endTransaction();
                    }
                    return Observable.just(null);
                }
                return Observable.create(new NetSubscribe(MyHttpClient.uploadJsonSport(workout2, fileName, md5, (curr, total) -> {
                    if (resultListener != null) {
                        resultListener.onProgress(workout2, curr, total);
                    }
                })));
            }).flatMap((Func1<String, Observable<Workout>>) s -> {

                try {
                    if (s == null){
                        throw new IllegalStateException("invalid workout");
                    }
                    JSONObject jSONObjectRaw = new JSONObject(s);
                    if (!jSONObjectRaw.has("data")) {
                        throw new IllegalStateException("sync result error");
                    }
                    JSONObject jSONObjectData = (JSONObject) jSONObjectRaw.get("data");
                    if (!jSONObjectData.has("workout")) {
                        throw new IllegalStateException("sync result error");
                    }
                    JSONObject jSONObject = (JSONObject) jSONObjectData.get("workout");

                    if (!jSONObject.has("serverId") || !jSONObject.has("credits")) {
                        throw new IllegalStateException("sync result error");
                    }

                    jSONObject.getString("uuid");
                    long serverId = jSONObject.getLong("serverId");
                    long lastUpload = jSONObject.getLong("lastUpload");
//                        jSONObject.getInt("uploadCount");//todo sst
                    double credits = jSONObject.getDouble("credits");
                    double creditsDvalue = jSONObject.getDouble("creditsDvalue");//todo sst
                    String thumbnail = jSONObject.getString("thumbnail");
                    String avg_heat_km_rate = jSONObject.getString("avgHeatKmRate");
                    double avg_heat_km = jSONObject.getDouble("avgHeatKm");

                    workout.setServerId(serverId);
                    workout.setLastUpload(lastUpload);
                    workout.setUploadStatus(Enums.UploadStatus.Uploaded);
                    workout.setUserId(App.getContext().getUserId());
                    workout.setCredits(credits);
                    workout.setCreditsDvalue(creditsDvalue);
                    workout.setThumbnail(thumbnail);
                    workout.setUploadTime(System.currentTimeMillis());
                    workout.setAvgHeatKmRate(avg_heat_km_rate);
                    workout.setAvgHeatKm(avg_heat_km);

                    LitePal.beginTransaction();

                    boolean result = workout.save();
                    for (Segment segment : Segment.getByWorkoutId(workout.getId())) {
                        segment.setUpload(true);
                        segment.save();
                    }

                    if (resultListener != null) {
                        resultListener.onResult(workout);
                    }

                    LitePal.setTransactionSuccessful();

                } catch (Exception e) {
                    e.printStackTrace();

                    if (resultListener != null) {
                        resultListener.onError(workout, e);
                    }

                } finally {
                    LitePal.endTransaction();
                }


                return null;
            }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
                @Override
                public void onCompleted() {
                    Log.d("SyncTaskService", "on Completed !");
                }

                @Override
                public void onError(Throwable th) {
                    th.printStackTrace();
                    if ((th instanceof NetSubscribe.ApiException) && ((NetSubscribe.ApiException) th).getBodyCode() == 20101) {
//                        ResultListener resultListener2 = resultListener;
                        if (resultListener != null) {
                            resultListener.onError(workout, th);
                        }
//todo sst check                        WorkoutDatabaseHelper.delete(workout);
                        return;
                    }
//                    File file = new File(fileName);
//                    if (file.exists()) {
//                        file.delete();
//                    }

                    if (resultListener != null) {
                        resultListener.onError(workout, th);
                    }
                    log("sync failed 254: " + th.getMessage(), th);
                }

                @Override
                public void onNext(Workout workout2) {

                    if (resultListener != null) {
                        resultListener.onResult(workout2);
                    }
                }
            }));
        }
//        if (!SharedManager.getInstance().isSyncQQHealth()) {
//            return true;
//        }
//        syncDataToQQHealth();
        return true;
    }

    @Override
    public boolean uploadXossGWorkout(List<Workout> list, final ResultListener<Workout, Workout> resultListener) {
        this.subscriptions = new ArrayList<>(list.size());
        for (int i = 0; i < list.size(); i++) {
            final Workout workout = list.get(i);
            this.subscriptions.add(Observable.just(workout).subscribeOn(Schedulers.io()).flatMap(new Func1<Workout, Observable<String>>() {
//                static final boolean $assertionsDisabled = false;

                @Override

                public Observable<String> call(final Workout workout2) {
                    if (workout2 != null) {
                        int sport = workout2.getSport();
                        if (sport == 1) {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_WALKING, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_WALKING, null, 1);
                        } else if (sport == 2) {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_RUNNING, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_RUNNING, null, 1);
                        } else if (sport == 3) {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_CYCLING, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_CYCLING, null, 1);
                        } else if (sport == 5) {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_SWIMMING, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_SWIMMING, null, 1);
                        } else if (sport == 6) {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_SKIING, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_SKIING, null, 1);
                        } else if (sport == 8) {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_TRAINING, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_TRAINING, null, 1);
                        } else {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_OTHER, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_OTHER, null, 1);
                        }
                    }
                    return Observable.create(new NetSubscribe(MyHttpClient.uploadFitWorkout(workout2, (j, j2) -> {
                        if (resultListener != null) {
                            resultListener.onProgress(workout2, j, j2);
                        }
                    })));
                }
            }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
//                static final boolean $assertionsDisabled = false;

                @Override
                public void onCompleted() {
                    Log.d("SyncTaskService", "on Completed !");
                }

                @Override
                public void onError(Throwable th) {
                    th.printStackTrace();
                    if (th instanceof NetSubscribe.ApiException) {
                        NetSubscribe.ApiException apiException = (NetSubscribe.ApiException) th;
                        if (apiException.getBodyCode() == 9006 || apiException.getBodyCode() == 9008
                                || apiException.getBodyCode() == 9009 || apiException.getBodyCode() == 9003) {
                            if (resultListener != null) {
                                resultListener.onError(workout, th);
                            }
                            WorkoutDatabaseHelper.delete(workout);
                            return;
                        }
                    }
                    if (resultListener != null) {
                        resultListener.onError(workout, th);
                    }
                    log("sync failed 357: " + th.getMessage(), th);
                }

                @Override
                public void onNext(String str) {
                    if (resultListener != null) {
                        try {
                            JSONObject jSONObject = new JSONObject(str);
//                            if (JsonUtil.getIntegerValue(a.i, jSONObject) != 0) {//todo, sst, need open it later
//                                return;
//                            }
                            JSONObject vData = JsonUtil.getObjectValue("data", jSONObject);
                            if (vData != null) {
                                long longValue = JsonUtil.getLongValue("workout_id", vData);
                                float longValue2 = (float) JsonUtil.getLongValue("credits", vData);
                                if (WorkoutDatabaseHelper.getWorkoutByServerId(longValue) == null) {
                                    workout.setServerId(longValue);
                                    workout.setUploadStatus(Enums.UploadStatus.Uploaded);
                                    workout.setUploadTime(System.currentTimeMillis());
                                    workout.setCredits(longValue2);
                                    WorkoutDatabaseHelper.save(workout);
                                } else {
                                    WorkoutDatabaseHelper.delete(workout);
                                }
                            }
                            resultListener.onResult(workout);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            log("save failed 376: " + e.getMessage(), e);
                        }
                    }
                }
            }));
        }
        if (SharedManager.getInstance().isSyncQQHealth()) {
            syncDataToQQHealth();
            return true;
        }
        return true;
    }

    @Override
    public boolean uploadFitWorkout(List<Workout> workouts, final ResultListener<Workout, Workout> listener) {
        this.subscriptions = new ArrayList<>(workouts.size());
        for (int i = 0; i < workouts.size(); i++) {
            final Workout workout = workouts.get(i);
            this.subscriptions.add(Observable.just(workout).subscribeOn(Schedulers.io()).flatMap(new Func1<Workout, Observable<String>>() {
//                static final boolean $assertionsDisabled = false;

                @Override

                public Observable<String> call(final Workout vWorkout) {
                    if (vWorkout != null) {
                        int sport = vWorkout.getSport();
                        if (sport == Workout.TYPE_WALKING) {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_WALKING, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_WALKING, null, 1);
                        } else if (sport == Workout.TYPE_RUNNING) {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_RUNNING, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_RUNNING, null, 1);
                        } else if (sport == Workout.TYPE_CYCLING) {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_CYCLING, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_CYCLING, null, 1);
                        } else if (sport == Workout.TYPE_SWIMMING) {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_SWIMMING, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_SWIMMING, null, 1);
                        } else if (sport == Workout.TYPE_SKIING) {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_SKIING, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_SKIING, null, 1);
                        } else if (sport == Workout.TYPE_TRAINING) {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_TRAINING, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_TRAINING, null, 1);
                        } else {
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_OTHER, null, 1);
                            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.V30_WORKOUT_UPLOAD_OTHER, null, 1);
                        }
                    }
                    return Observable.create(new NetSubscribe(MyHttpClient.uploadFitWorkout(vWorkout, (j, j2) -> {
                        if (listener != null) {
                            listener.onProgress(vWorkout, j, j2);
                        }
                    })));
                }
            }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
//                static final boolean $assertionsDisabled = false;

                @Override
                public void onCompleted() {
                    Log.d("SyncTaskService", "on Completed !");
                }

                @Override
                public void onError(Throwable th) {
                    log("sync error: ", th);
                    th.printStackTrace();
                    if (th instanceof NetSubscribe.ApiException apiException) {
                        if (apiException.getBodyCode() == 9006 || apiException.getBodyCode() == 9008
                                || apiException.getBodyCode() == 9009 || apiException.getBodyCode() == 9003) {
                            if (listener != null) {
                                listener.onResult(workout);
                            }
                            WorkoutDatabaseHelper.delete(workout);
                            return;
                        }
                    }
                    if (listener != null) {
                        listener.onError(workout, th);
                    }
                    log("sync failed 474: " + th.getMessage(), th);
                }

                @Override
                public void onNext(String str) {
                    if (listener != null) {
                        try {
                            JSONObject jSONObject = new JSONObject(str);
//                            if (JsonUtil.getIntegerValue(a.i, jSONObject) != 0) {//todo sst, need open it later
//                                return;
//                            }
                            JSONObject vData = JsonUtil.getObjectValue("data", jSONObject);

                            if (vData != null) {
                                long vServerId = JsonUtil.getLongValue("workout_id", vData);
                                float vCredits = (float) JsonUtil.getLongValue("credits", vData);
                                if (WorkoutDatabaseHelper.getWorkoutByServerId(vServerId) == null) {
                                    workout.setServerId(vServerId);
                                    workout.setUploadStatus(Enums.UploadStatus.Uploaded);
                                    workout.setUploadTime(System.currentTimeMillis());
                                    workout.setCredits(vCredits);
                                    WorkoutDatabaseHelper.save(workout);
                                } else {
                                    WorkoutDatabaseHelper.delete(workout);
                                }
                            }
                            listener.onResult(workout);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            log("save failed 496: " + e.getMessage(), e);
                        }
                    }
                }
            }));
        }
        if (SharedManager.getInstance().isSyncQQHealth()) {
            syncDataToQQHealth();
            return true;
        }
        return true;
    }

    @Override
    public void cancelUpload() {
        ArrayList<Subscription> arrayList = this.subscriptions;
        if (arrayList == null || arrayList.isEmpty()) {
            return;
        }
        Iterator<Subscription> it = this.subscriptions.iterator();
        while (it.hasNext()) {
            Subscription next = it.next();
            if (!next.isUnsubscribed()) {
                next.unsubscribe();
            }
        }
        this.subscriptions = null;
    }


    public String createUploadPackage(Workout workout, String fileName) throws IOException {
        List<Segment> unupload = Segment.getUnupload(workout.getId());
        long uploadedCount = Segment.getUploadedCount(workout.getId());
        List<Trackpoint> queryUnUploadPoint = queryUnUploadPoint(workout.getId(), 200000L, uploadedCount);
        List<PacePoint> queryPacePoint = WorkoutDatabaseHelper.queryPacePoint(workout.getUuid());
        Log.d(TAG, "unUpload points size = " + queryUnUploadPoint.size() + " segment size = " + unupload.size() + " , lastUpload = " + uploadedCount);
        Writer writer = null;
        if (unupload.size() == 0 || queryUnUploadPoint.size() == 0) {
            return null;
        }
        JPointPackage jPointPackage = new JPointPackage();
        jPointPackage.setVersion(1);
        jPointPackage.setDevice_info(App.getContext().getDeviceInfo());

        jPointPackage.setWorkout(JWorkout.create(workout));

        ArrayList<JSegment> arrayList = new ArrayList<>();
        for (Segment segment : unupload) {
            arrayList.add(JSegment.create(segment));
        }
        jPointPackage.setSegments(arrayList);

        ArrayList<JPoint> arrayList2 = new ArrayList<>();
        for (Trackpoint trackpoint : queryUnUploadPoint) {
            arrayList2.add(JPoint.create(trackpoint));
        }
        jPointPackage.setPoints(arrayList2);

        ArrayList<JSegmentKm> arrayList3 = new ArrayList<>();
        for (PacePoint pacePoint : queryPacePoint) {
            arrayList3.add(JSegmentKm.create(pacePoint));
        }
        jPointPackage.setSegments_km(arrayList3);

        try {
            try {
                writer = AppFileUtils.getGZIPWriter(fileName);
                JSON.writeJSONString(writer, jPointPackage);
                writer.flush();
                return CommonUtil.getMD5(new File(fileName));
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e2) {
            e2.printStackTrace();
            throw new IOException("create JPoint Package failed !", e2);
        }
    }

    private List<Trackpoint> queryUnUploadPoint(long workoutId, long size, long uploadedCount) {
        long countTackPoint = WorkoutDatabaseHelper.countTackPoint(workoutId);
        long j = countTackPoint - uploadedCount;
        String[] strArr = {"accuracy", "altitude", "bearing", "latitude", "longitude", "speed", "time", "id", "workoutid", "cadence", "wheelrpm", "heartrate", "pressure", "temperature", "power", "powerext", "distanceeach", "durationeach", "pointtype", "distance", "duration", "elevationgain", "elevationloss"};
        if (j > size) {
            List<Trackpoint> queryTrackPoint = WorkoutDatabaseHelper.queryTrackPoint(workoutId, 1L, uploadedCount);
            if (queryTrackPoint == null || queryTrackPoint.isEmpty()) {
                return new ArrayList();
            }
            Trackpoint trackpoint = queryTrackPoint.get(0);
            List<Trackpoint> queryTrackPoint2 = WorkoutDatabaseHelper.queryTrackPoint(workoutId, 1L, countTackPoint - 1);
            if (queryTrackPoint2 == null || queryTrackPoint2.isEmpty()) {
                return new ArrayList();
            }
            long longValue = trackpoint.getId();
            long longValue2 = queryTrackPoint2.get(0).getId();
            int ceil = (int) Math.ceil(((float) j) / ((float) size));
            return WorkoutDatabaseHelper.queryTrackPoint(strArr, "workoutid = ? AND id >= ? AND (id % ? = " + ((int) (longValue % ceil)) + " OR id = ?)", new String[]{String.valueOf(workoutId), String.valueOf(longValue), String.valueOf(ceil), String.valueOf(longValue2)}, null, 0L, 0L);
        }
        return WorkoutDatabaseHelper.queryTrackPoint(workoutId, strArr, j, uploadedCount);
    }

    private void syncDataToQQHealth() {
        Callback callback;
        int i;
        List<Workout> todaysWorkouts = Workout.getTodaysWorkouts(App.getContext().getUserId());
        Log.d("getTodaysWorkouts workouts size = " + todaysWorkouts.size());
        int i2 = 0;
        double d = 0.0d;
        double d2 = 0.0d;
        double d3 = 0.0d;
        int i3 = 0;
        int i4 = 0;
        int i5 = 0;
        int i6 = 0;
        int i7 = 0;
        for (Workout workout : todaysWorkouts) {
            int sport = workout.getSport();
            if (sport == Workout.TYPE_WALKING) {
                d += workout.getDistance();
                i4 += workout.getCalorie() / 1000;
                i3 = (int) (i3 + workout.getDuration());
            } else if (sport == Workout.TYPE_RUNNING) {
                d2 += workout.getDistance();
                i2 = (int) (i2 + workout.getDuration());
                i6 += workout.getCalorie() / 1000;
            } else if (sport == Workout.TYPE_CYCLING) {
                d3 += workout.getDistance();
                i7 += workout.getCalorie() / 1000;
                i5 = (int) (i5 + workout.getDuration());
            }
        }
        User signinUser = App.getContext().getSigninUser();
        String decodeThirtPartyAccessToken = CommonUtil.decodeThirtPartyAccessToken(signinUser.getQq());
        String decodeThirtPartyOpenId = CommonUtil.decodeThirtPartyOpenId(signinUser.getQq());
        Callback callback2 = new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.d(TAG, " response : " + response + " body : " + string);
            }
        };
        if (d > Utils.DOUBLE_EPSILON && i3 > 0) {
            TencentClient.syncQQHealth(callback2, decodeThirtPartyAccessToken, decodeThirtPartyOpenId, 1, d, i3, (d / i3) * 3.6d, i4);
        }
        if (d2 <= Utils.DOUBLE_EPSILON || i2 <= 0) {
            callback = callback2;
            i = i5;
        } else {
            callback = callback2;
            i = i5;
            TencentClient.syncQQHealth(callback2, decodeThirtPartyAccessToken, decodeThirtPartyOpenId, 2, d2, i2, 3.6d * (d2 / i2), i6);
        }
        if (d3 <= Utils.DOUBLE_EPSILON || i <= 0) {
            return;
        }
        TencentClient.syncQQHealth(callback, decodeThirtPartyAccessToken, decodeThirtPartyOpenId, 3, d3, i, d3 / i, i7);
    }
}
